
package br.usp.icmc.client.dao;
 

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.hibernate.Session;

 public abstract class HibernateAbstractDAO<T extends Serializable, KeyType extends Serializable>  
     implements AbstractDAO<T, KeyType>  {  
   
     @SuppressWarnings(value = "unchecked")  
     protected Class<T> domainClass = getDomainClass();  
   
     public HibernateAbstractDAO() {  
     }  
   
     @SuppressWarnings(value = "unchecked")  
     public T load(KeyType id) {  
         return ((T)getSession().load(domainClass, id));  
     }  
   
     public abstract List<T> select(String key);
     
     public void update(T obj) {  
         HibernateUtility.beginTransaction();
         getSession().update(obj); 
         HibernateUtility.commitTransaction();  
     }  
   
     public void save(T obj) {  
         HibernateUtility.beginTransaction();  
         getSession().save(obj);  
         HibernateUtility.commitTransaction();
     }  
   
     public void saveOrUpdate(T obj) {  
         HibernateUtility.beginTransaction();  
         getSession().saveOrUpdate(obj);  
         HibernateUtility.commitTransaction();  
     }  
   
     public void saveOrUpdateNoCommit(T obj) {  
         HibernateUtility.beginTransaction();  
         getSession().saveOrUpdate(obj);  
     }  
     
     public void delete(T t) {  
         getSession().delete(t);  
     }  
   
     @SuppressWarnings(value = "unchecked")  
     public List<T> getList() {  
         Session s = getSession();  
        return(s.createCriteria(domainClass).list());  
     }  
   
     public void deleteById(KeyType id) {  
         Object obj = load(id);
         HibernateUtility.beginTransaction();
         getSession().delete(obj);  
         HibernateUtility.commitTransaction();  
     }  
     
     public void deleteAll() {  
         getSession().createQuery("delete " + domainClass.getName()).executeUpdate();  
     }  
   
     public int count() {  
         List list = getSession().createQuery("select count(*) from " + domainClass.getName() + " x").list();  
         Integer count = (Integer) list.get(0);  
         return(count.intValue());  
     }  
   
     protected Session getSession() {  
         return(HibernateUtility.getSession());  
     }  
   
     @SuppressWarnings(value = "unchecked")  
     protected Class getDomainClass() {  
         if (domainClass == null) {  
             ParameterizedType thisType = (ParameterizedType) getClass().getGenericSuperclass();  
             domainClass = (Class) thisType.getActualTypeArguments()[0];  
         }  
         return domainClass;  
     }  
 }  
  

